//
//  MeatPayViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/29.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatPayViewController.h"
#import "MeatPaySuccessViewController.h"
#import "TopUpViewController.h"

#import "MeatOrderTimerCell.h"

#import "MeatMarketApi.h"
#import "MeatPayOrderModel.h"
#import "TJTimer.h"



@interface MeatPayViewController ()

/**
 tap
 */
@property (nonatomic, strong) UITapGestureRecognizer *tap;


/**
 footer
 */
@property (nonatomic, strong) UIView *footer;


/**
 icons
 */
@property (nonatomic, strong) NSArray *icons;


/**
 titles
 */
@property (nonatomic, strong) NSArray *titles;


/**
 textfield
 */
@property (nonatomic, strong) UITextField *textField; //


@property (nonatomic, strong) MeatMarketApi *meatApi;


@property (nonatomic, strong) MeatOrderModel *orderModel;


@property (nonatomic, strong) UITableViewCell *aimCell;

@property (nonatomic, strong) MeatOrderTimerCell *timerCell;

@property (nonatomic, strong) TJTimer *timer;

@property (nonatomic, copy) NSString *payType;

@property (nonatomic, copy) NSString *resetMoney;



@end

@implementation MeatPayViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    self.baseNavView.navTitleLabel.text = @"确认订单";
    self.aimCell = nil;
    self.resetMoney = @"0";
    [self addkeyBoardNotification];
}


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self requestUserPrice];
}


#pragma mark - networking methods

- (void)initData{
    
    @weakify(self);
    [[self.meatApi getMeatPayOrderSumbitByParams:self.parma] subscribeNext:^(MeatOrderModel * _Nullable model) {
        @strongify(self);
        self.orderModel = model;
        int time = [NSString dateTimeDifferenceWithStartTime:model.createTime endTime:model.invalidTime];
        self.timer.time = time;
        [self.timer startTimer];

    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}


- (void)submitPay{

    @weakify(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认放弃付款吗？" message:@"超过支付时效后，订单会被取消哦" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定离开" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [cancelAction setValue:UIColorFromRGB(0x363636) forKey:@"titleTextColor"];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"继续支付" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

        @strongify(self);
        [self requestPayOrder];
    }];
    [okAction setValue:mMainColor forKey:@"titleTextColor"];

    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}
                                   

- (void)requestPayOrder{
    
    double price = [self.orderModel.price doubleValue];
    
    if (price <0 ) {
        [self showHudWithMsg:@"下单金额不能为0"];
        return;
    }
    
    if([self.payType integerValue] == 2 || [self.payType integerValue] == 3)
    {
        [self showHudWithMsg:@"目前暂不支持微信/支付宝"];
        return;
    }
    
    @weakify(self);
    [self showProgressView];
    [[self.meatApi getMeatPayByOrderId:self.orderModel.orderId payAmount:@(price)  payType:self.payType] subscribeNext:^(PigTypeModel * _Nullable x) {
        @strongify(self);
        [self hideProgressView];
        MeatPaySuccessViewController *vc = [[MeatPaySuccessViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } error:^(NSError * _Nullable error) {
        [self hideProgressView];
    }];
}

- (void)requestUserPrice {
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getMyAssetWithMemberId:memberId] subscribeNext:^(MyAsset * _Nullable myAsset) {
        @strongify(self);
    
        [kUserDefaults setObject:myAsset.money forKey:kUserPrice];
        [kUserDefaults synchronize];
        NSString *price = [NSString stringWithFormat:@"可用余额%@元", [kUserDefaults stringForKey:kUserPrice]];
        self.titles = @[@[@"微信支付", @"支付宝"],  @[@"余额支付", @"¥", price], @[@"微信好友代付"]];
        
        [self localReloadTableViewBySection:2];

    } ];
}



#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger row = 1;
    if (section == 1) {
        row = 3;
    }else if (section == 2){
        return row = 4;
    }else if (section == 3){
        return 2;
    }
    return row;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) return 79;
    return indexPath.row == 0 ?32 : 54;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath .section == 0) {
        
        MeatOrderTimerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatOrderTimerCell"];
        self.timerCell = cell;
        [cell setPrice:self.parma.payAmount];
        
        return cell;
    }
    
    
    UITableViewCell *newsCell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    newsCell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (!newsCell) {
        newsCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"];
    }
    newsCell.textLabel.font = mFont(15);
    
    if (indexPath.row != 0) {
        
        newsCell.accessoryView = ({
            UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"meat_cart_unchecked"]];
            CGRect frame = imgV.frame;
            frame.size = CGSizeMake(18, 18);
            imgV.frame = frame;
            [imgV setContentMode:UIViewContentModeLeft];
            imgV;
        });
    }
    
    if (indexPath.section == 1) {
        
        if (indexPath.row == 0) {
            newsCell.textLabel.text = @"第三方支付方式";
            newsCell.textLabel.textColor = UIColorFromRGB(0x969696);
            newsCell.backgroundColor = mBackgroudColor;
            newsCell.textLabel.font = mFont(14);
            
            if ([newsCell respondsToSelector:@selector(setSeparatorInset:)]) {
                [newsCell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            }

        }else{
            
            newsCell.textLabel.textColor = UIColorFromRGB(0x333333);
            newsCell.textLabel.text = self.titles[0][indexPath.row - 1];
            newsCell.imageView.image = [UIImage imageNamed:self.icons[0][indexPath.row - 1]];
        }
    }
    
    if (indexPath.section == 2) {
        
        if (indexPath.row == 0) {
            newsCell.textLabel.text = @"账户支付";
            newsCell.textLabel.textColor = UIColorFromRGB(0x969696);
            newsCell.textLabel.font = mFont(14);
            newsCell.backgroundColor = mBackgroudColor;

            if ([newsCell respondsToSelector:@selector(setSeparatorInset:)]) {
                [newsCell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            }

        }else{
           
            newsCell.textLabel.textColor = indexPath.row == 3 ?UIColorFromRGB(0x999999) :UIColorFromRGB(0x333333);
            newsCell.textLabel.font = indexPath.row == 3 ?mFont(12) :mFont(15);

            newsCell.textLabel.text = self.titles[1][indexPath.row - 1];
            newsCell.imageView.image = [UIImage imageNamed:self.icons[1][indexPath.row - 1]];
            newsCell.imageView.hidden = indexPath.row == 1? NO :YES;
            newsCell.accessoryView.hidden = indexPath.row != 3 ?NO :YES;
            
            
            if (indexPath.row == 2) {
                
                [newsCell addSubview:self.textField];
                newsCell.accessoryView = ({
                    UIButton *button = [UIButton makeButtonWithText:@"去充值" textColor:mMainColor font:mFont(12) textAliment:1 cornerRadius:5];
                    button.layer.borderWidth = 1;
                    button.layer.borderColor = mMainColor.CGColor;
                    CGRect frame = button.frame;
                    frame.size = CGSizeMake(56, 27);
                    button.frame = frame;
                    [button setContentMode:UIViewContentModeLeft];
                    
                    @weakify(self);
                    button.tapBlock = ^{
                        @strongify(self);
                        
                        float price = [self.resetMoney floatValue];
                        if (price <=0) {
                            [self showHudWithMsg:@"请输入充值金额"];
                            return;
                        }
                        
                        TopUpViewController *vc = [[TopUpViewController alloc] init];
                        vc.price = self.resetMoney;
                        [self.navigationController pushViewController:vc animated:YES];
                        
                    };
                    button;
                });
            }
        }
    }
    
    if (indexPath.section == 3) {
        
        if (indexPath.row == 0) {
            newsCell.textLabel.text = @"朋友代付";
            newsCell.textLabel.textColor = UIColorFromRGB(0x969696);
            newsCell.backgroundColor = mBackgroudColor;
            newsCell.textLabel.font = mFont(14);

            
            if ([newsCell respondsToSelector:@selector(setSeparatorInset:)]) {
                [newsCell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            }
            
        }else{
            
            newsCell.textLabel.textColor = UIColorFromRGB(0x333333);
            newsCell.textLabel.text = self.titles[2][indexPath.row - 1];
            newsCell.imageView.image = [UIImage imageNamed:self.icons[2][indexPath.row - 1]];
        }
    }

    return newsCell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    BOOL checked = (indexPath.section == 2 &&indexPath.row == 3) ||(indexPath.section == 2 && indexPath.row == 2);
    
    if (!checked){
        
        UITableViewCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
        if (cell.accessoryView && !cell.accessoryView.hidden) {
            cell.accessoryView = ({
                UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"meat_pay_choosed"]];
                CGRect frame = imgV.frame;
                frame.size = CGSizeMake(18, 18);
                imgV.frame = frame;
                [imgV setContentMode:UIViewContentModeLeft];
                imgV;
            });
        }
        
        if (self.aimCell == nil) {
            self.aimCell = cell;
        }else{
            
            self.aimCell.accessoryView = ({
                UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"meat_cart_uncheckedv"]];
                CGRect frame = imgV.frame;
                frame.size = CGSizeMake(18, 18);
                imgV.frame = frame;
                [imgV setContentMode:UIViewContentModeLeft];
                imgV;
            });
            self.aimCell = cell;
        }
        
        switch (indexPath.section) {
            case 1:
            {
                self.payType = indexPath.row == 1? @"3":@"2";
            }
                break;
            case 2:
            {
                self.payType = @"1";
            }
                break;
            default:
                break;
        }
        
        if (indexPath.section == 3) {
            [self showHudWithMsg:@"朋友代付"];
        }
    }
}


#pragma mark - setter and getter

- (TJTimer *)timer{
    if (!_timer) {
        _timer = [[TJTimer alloc] init];
        _timer.time = 0;
        
        @weakify(self);
        
        _timer.doingBlock = ^(NSInteger params) {
            @strongify(self);
            
            NSString *str_hour = [NSString stringWithFormat:@"%02ld",params/3600];
            NSString *str_minute = [NSString stringWithFormat:@"%02ld",(params%3600)/60];
            NSString *str_second = [NSString stringWithFormat:@"%02ld",params%60];
            self.timerCell.shiLab.text = str_hour;
            self.timerCell.fenLab.text = str_minute;
            self.timerCell.miaoLab.text = str_second;
        };
        
        _timer.endBlock = ^{
            @strongify(self);
            [self showHudWithMsg:@"定时器结束"];
        };
    }
    return _timer;
}

#pragma mark - override methods

- (void)registerTableViewCell{
    
    self.tableView.height = KScreenHeight - (TJ_NavBarHeight);
    self.tableView.mj_y = self.baseNavView.bottom;
    self.tableView.tableFooterView = self.footer;
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.mj_footer = nil;
    self.tableView.mj_header = nil;
    [self.tableView registerClass:[MeatOrderTimerCell class] forCellReuseIdentifier:@"MeatOrderTimerCell"];
}


- (UIView *)footer{
    if (!_footer) {
        _footer = [[UIView alloc] init];
        _footer.backgroundColor = mBackgroudColor;
        _footer.frame = CGRectMake(0, 0, KScreenWidth, 148);
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"去支付" forState:UIControlStateNormal];
        [button setTitleColor:KWhiteColor forState:UIControlStateNormal];
        button.titleLabel.font = mMediumFont(16);
        UIImageView *bg = [[UIImageView alloc] init];
        bg.image = [UIImage imageNamed:@"meat_buy_bg"];
        bg.frame = CGRectMake(0, 0, KScreenWidth - 60, 48);
        [self addShadowAndCircleCorner:bg.layer corner:5];

        [button insertSubview:bg atIndex:0];
        button.frame = CGRectMake(30, 50, KScreenWidth -60, 48);
        
        [button addTarget:self action:@selector(submitPay) forControlEvents:UIControlEventTouchUpInside];
        [_footer addSubview:button];
    }
    return _footer;
}


- (UITextField *)textField {
    
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.placeholder = @"本次充值最多可以充值多少元";
        _textField.font = mFont(12);
        _textField.size = CGSizeMake(200, 54);
        _textField.mj_x = 70;
        _textField.mj_y = 0;
        _textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _textField;
}


- (NSArray *)icons{
    
    if (!_icons) {
        _icons = @[@[@"meat_pay_alipay", @"meat_pay_wechat"],  @[@"meat_pay_yue", @"meat_pay_yue", @"meat_pay_yue"], @[@"meat_friend_pay"]];
    }
    return _icons;
}


- (NSArray *)titles{
    
    if (!_titles) {
        
        NSString *price = [NSString stringWithFormat:@"可用余额%@元", [kUserDefaults stringForKey:kUserPrice]];
        _titles = @[@[@"微信支付", @"支付宝"],  @[@"余额支付", @"¥", price], @[@"微信好友代付"]];
    }
    return _titles;
}


- (MeatMarketApi *)meatApi{
    
    if(!_meatApi){
        _meatApi = [[MeatMarketApi alloc]init];
    }
    return _meatApi;
}


- (MeatOrderModel *)orderModel{
    
    if (!_orderModel) {
        _orderModel = [[MeatOrderModel alloc] init];
    }
    return _orderModel;
}


#pragma mark - notification methods

- (void)textFieldTextChanged:(NSNotification *)notification
{
    UITextField *textField = notification.object;
    self.resetMoney = textField.text;
}

- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    kWeakSelf(self);
    [UIView animateWithDuration:duration animations:^{
        weakself.tableView.mj_y = 0;
    }];
    
    //当键盘升起的时候添加点击降落操作
    if (!self.tap) {
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    }
    [self.view addGestureRecognizer:self.tap];
}

//取消键盘响应
- (void)hideKeyboard{
    
    [self.view endEditing:YES];
}


- (void)keyboardWillHide:(NSNotification *)notification{
    
    self.tableView.mj_y = TJ_NavBarHeight;
    if (self.tap) {
        [self.view removeGestureRecognizer:self.tap];
    }
}


//添加键盘通知
- (void)addkeyBoardNotification{
    
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

//移除键盘通知
- (void)removeKeyboardNotification{
    
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc{
    
    [self removeKeyboardNotification];
}


@end
